package com.me.web;

import com.me.domain.User;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public abstract class BaseServlet extends HttpServlet {
    private HttpServletRequest req;
	private HttpServletResponse resp;
	private HttpSession session;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.req = req;
		this.resp = resp;
		this.session = req.getSession();

		if (req.getMethod().toLowerCase().equals("post")) {
			doPost();
		} else {
			doGet();
		}

	}

	protected abstract void doGet()throws ServletException, IOException;

	protected abstract void doPost()throws ServletException, IOException;



    protected String getParam(String param){
        return req.getParameter(param);
    }

	protected int getIntParam(String param) {
		return Integer.parseInt(getParam(param));
	}

	protected String[] getParamVals(String param) {
    	return req.getParameterValues(param); }

    protected Object getSesAttr(String param) {
        return session.getAttribute(param);
    }

    protected void setSesAttr(String key,Object val) {
        session.setAttribute(key,val);
    }

    protected void setReqAttr(String key,Object val){
        req.setAttribute(key,val);
    }

	protected void forward(String url) throws ServletException, IOException {
		if (url.startsWith(".")) {
			resp.sendRedirect(url.substring(1));
		} else {
			req.getRequestDispatcher(url).forward(req, resp);
		}
	}

	protected void clearSes() {
		session.invalidate();
	}

	protected Part getPart(String val) throws IOException, ServletException {
    	return req.getPart(val);
	}

	protected User getSesUser() {
		return (User)getSesAttr("user");
	}
}
